package com.bangcommunity.bbframe.springredis.id;

import com.bangcommunity.bbframe.common.utils.id.DangDangIdFactory;
import com.bangcommunity.bbframe.dynconfig.lock.ZkLock;
import com.bangcommunity.bbframe.springredis.RedisClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by tanghc on 17/1/23.
 */
public class RedisZkId {
    static final Logger logger = LoggerFactory.getLogger(RedisZkId.class);

    private RedisZkId() {
    }

    private static class RedisZkIdHolder {
        private static RedisZkId instance = new RedisZkId();
    }

    public static RedisZkId getInstance() {
        return RedisZkIdHolder.instance;
    }

    public long nextId(String key,int delta){
        String redisKey = "ids:"+key;
        Long incr = RedisClient.incr(redisKey, delta);
        if(null == incr || incr < 100000000){
            ZkLock.getInstance().execute(redisKey, 10000, () -> {
                long l = DangDangIdFactory.getInstance().getIdGenerator(redisKey).generateId();
                RedisClient.setIncr(redisKey, l);
                return null;
            });
            return RedisClient.incr(redisKey, delta);
        }
        return incr;
    }
    public long nextId(String key){
        return nextId(key,1);
    }

}
